<?php

namespace app\controllers\h5\execute;

use app\controllers\h5\base\H5Controller;
use app\models\marketing\MarketingBasic;
use app\models\user\User;
use app\models\user\UserRefill as Model;

class RefillController extends H5Controller
{
    /**
     * fetch refill
     *
     * @return array|string[]|\yii\web\Response
     */
    public function actionFetch()
    {
        $set = MarketingBasic::getLastOne();
        $user = User::find()
            ->where(['id' => $this->user->id])
            ->select(['id', 'nickname', 'mobile'])
            ->asArray()
            ->one();

        return $this->successEncode([
            'mini' => floatval($set->refill_min_amount),
            'user' => $user
        ]);
    }

    /**
     * create refill order
     *
     * @return array|string[]|\yii\web\Response
     */
    public function actionCreateOrder()
    {
        $amount = floatval($this->post('amount'));
        $set = MarketingBasic::getLastOne();

        if ($amount < $set->refill_min_amount) {
            return $this->fail('充值金额不能小于' . $set->refill_min_amount);
        }

        $model = new Model();
        $model->sn = Model::generateSn();
        $model->user_id = $this->user->id;
        $model->amount = $amount;
        $model->status = 0;
        if ($model->save()) {
            return $this->successEncode([
                'user_refill_id' => $model->id
            ]);
        }

        return $this->fail();
    }

    /**
     * get refill pay amount
     *
     * @return array|string[]|\yii\web\Response
     */
    public function actionGetAmount()
    {
        $id = $this->post('user_refill_id');

        $model = Model::find()
            ->where(['id' => $id, 'user_id' => $this->user->id])
            ->andWhere(['status' => Model::$statusMapping['NOT']])
            ->asArray()
            ->one();

        if ($model) {
            return $this->successEncode($model);
        }

        return $this->fail();
    }
}